/**
 * 判断是否有参数缺少
 * @param {Object} ctx ctx对象
 * @param {String} file 报错文件
 * @param {Array} requireArr 必填参数数组
 * @param {Object} dataObj 收到的参数对象
 */
function judgeIfMissParam(ctx, file, requireArr, dataObj) {
  if (!Array.isArray(requireArr)) 
    return console.log('[common——judgeIfMissParam] 传入的requireArr必须为一个数组');
  if (Object.prototype.toString.call(dataObj) !== '[object Object]') 
    return console.log('[common——judgeIfMissParam] 传入的dataObj必须为一个对象');
  let symbol = true, detail;
  console.log(requireArr, dataObj);
  try {
    for (let i = 0; i < requireArr.length; i++) {
      if (!(requireArr[i] in dataObj)) {
        symbol = false;
        detail = requireArr[i];
        console.log(`[LOG] ${detail}_is_missing`);
        const error = new Error(`1004 ${file}`);
        ctx.app.emit('error', error, ctx);
      }
    }
    return symbol;
  }catch (e) {
    console.log('[common]', e);
  }
}

/**
 * 为字符串添加0
 * @param {String || Int} data 传入的字符串
 * @returns 
 */
function add0(data) {
  return data < 10 ? '0'+ data : data;
}

/**
 * 时间戳转换为 xxxx-xx-xx xx:xx:xx
 * @param {String} timestamp 时间戳
 * @returns 
 */
function formatTimestamp (timestamp) {
  const time = new Date(parseInt(timestamp));
  const y = time.getFullYear();
  const m = time.getMonth() + 1;
  const d = time.getDate();
  const h = time.getHours();
  const min = time.getMinutes();
  const s = time.getSeconds();
  // console.log(`${y}-${add0(m)}-${add0(d)} ${add0(h)}:${add0(min)}:${add0(s)}`);
  return `${y}-${add0(m)}-${add0(d)} ${add0(h)}:${add0(min)}:${add0(s)}`;
}


function getMonthDate() {
  const date = new Date();
  const year = date.getFullYear();
  let month = date.getMonth() + 1;
  month = month < 10 ? '0' + month : month.toString();
  // 获取月初时间
  const curMonthFirstDate = `${year}-${month}-01 00:00:00`;
  // 设置月末时间戳
  let monthStartTimestamp = new Date(curMonthFirstDate).getTime();
  let monthEndTimestamp = '';
  let dayTimestamp = 24 * 60 * 60 * 1000;
  if (['01', '03', '05', '07', '08', '10', '12'].indexOf(month) !== -1) { // 判断当前月份是否为大月
    monthEndTimestamp = monthStartTimestamp + 31 * dayTimestamp - 1;
  } else if (['04', '06', '09', '11'].indexOf(month) !== -1) {
    monthEndTimestamp = monthStartTimestamp + 30 * dayTimestamp - 1;
  } else if (month === '02') {
    const day = year % 4 === 0 ? 29 : 28;
    monthEndTimestamp = monthStartTimestamp + day * dayTimestamp - 1;
  }
  // 获取月末时间
  let curMonthLastDate = formatTimestamp(monthEndTimestamp);
  return [curMonthFirstDate, curMonthLastDate];
}

module.exports = {
  judgeIfMissParam,
  formatTimestamp,
  getMonthDate
}